import { showModal, showToast, requestPayment } from '../../utils/asyncWx'
import { request } from '../../request/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //地址的数据
    address: {},
    //购物车的数据
    cart: [],
    //控制全选

    //总价格
    totalPrice: 0,
    // 总数量
    totalNum: 0,

  },
  onShow () {


    //获取缓存中的数据
    let address = wx.getStorageSync('address')
    // 获取缓存中购物车的数据
    let cart = wx.getStorageSync('cart') || []
    // 过滤check为true的数据，只渲染这些数据
    cart = cart.filter(v => v.checked)
    this.setData({
      address,
    })

    //总价格和总数量 
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price
      totalNum += v.num
    })
    //把修改好的数据设置会data和缓存中
    this.setData({
      cart,
      totalPrice,
      totalNum,

      address
    })
  },
  //点击支付按钮
  async handleOrderPay () {
    try {
      // 判断是否有token值，没有就需要授权获取，有就跳到支付
      const token = wx.getStorageSync('token')
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index',
        })
        return
      }
      //  准备参数
      // const header = { Authorization: token }
      const order_price = this.data.totalPrice
      const address = this.data.address
      const consignee_addr = address.provinceName + address.cityName + address.countyName + address.detailInfo
      const cart = this.data.cart
      let goods = []
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods }

      // 准备发送请求  data要放对象，orderParams已经是对象，order_number还不是对象，所以order_number要加{}
      //  创建订单 获取订单偏号
      const order = await request({ url: "/my/orders/create", method: "POST", data: orderParams })
      const order_number = order.data.message.order_number
      //  发起预支付接口
      const { pay } = (await request({ url: "/my/orders/req_unifiedorder", method: "POST", data: { order_number } })).data.message
      // 发起微信支付
      await requestPayment(pay)
      // 查询订单状态
      const res = await request({ url: "/my/orders/chkOrder", method: "POST", data: { order_number } })
      console.log(res);
      await showToast({ title: "支付成功" })
      //删除缓存中已经支付的商品
      let newCart = wx.getStorageSync('cart')
      newCart = newCart.filter(v => !v.checked)//过滤器，因为有有个！所以留下那些未被选中的
      wx.setStorageSync('cart', newCart)

      // 支付成功跳转到订单页面
      wx.navigateTo({
        url: '/pages/order/index',
      })
    } catch (error) {
      await showToast({ title: "支付失败" })

      console.log(error);
    }


  }


})